package com.zhongfl.crm.lixiao.config;

import com.heptagram.lixiao.api.LiXiaoInMemoryConfigStorage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @author wang.yuchuan
 * @date 2018/6/22
 */
@Slf4j
public class LiXiaoRedisConfigStorage extends LiXiaoInMemoryConfigStorage {

    public static final String LI_XIAO_ACCESS_TOKEN_REDIS_KEY = "work-order-manager:lixiao:access-token-key";

    //redis存放
    private RedisTemplate<String, String> redisTemplate;

    public LiXiaoRedisConfigStorage(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public String getAccessToken() {
        String userToken = redisTemplate.opsForValue().get(LI_XIAO_ACCESS_TOKEN_REDIS_KEY);
        log.info("从Redis中获取励销user_token: {}", userToken);
        return userToken;
    }

    @Override
    public void setAccessToken(String accessToken) {
        redisTemplate.opsForValue().set(LI_XIAO_ACCESS_TOKEN_REDIS_KEY, accessToken, 30, TimeUnit.DAYS);
        log.info("更新Redis中励销user_token: {}", accessToken);
    }

    @Override
    public boolean isAccessTokenExpired() {
        return redisTemplate.getExpire(LI_XIAO_ACCESS_TOKEN_REDIS_KEY) < 2;
    }

    @Override
    public synchronized void updateAccessToken(String accessToken, int expiresInDays) {
        redisTemplate.opsForValue().set(LI_XIAO_ACCESS_TOKEN_REDIS_KEY, accessToken, 1, TimeUnit.DAYS);
        log.info("更新Redis中励销user_token: {}", accessToken);
    }

    @Override
    public void expireAccessToken() {
        redisTemplate.opsForValue().getOperations().delete(LI_XIAO_ACCESS_TOKEN_REDIS_KEY);
        log.info("清空Redis中励销user_token");
    }
}
